package com.zhilianbao.leyaogo.ui.fragment.me.userinfo;

import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.bql.commonrow.CommonCircleRightListRow;
import com.bql.commonrow.CommonListRow;
import com.bql.pickerview.TimePickerView;
import com.bql.pickphotos.PickPhotos;
import com.bql.utils.CheckUtils;
import com.bql.utils.DateUtils;
import com.bql.utils.EventManager;
import com.bql.utils.StringUtils;
import com.bql.utils.ThreadPool;
import com.luck.picture.lib.model.FunctionConfig;
import com.luck.picture.lib.model.PictureConfig;
import com.zhilianbao.leyaogo.R;
import com.zhilianbao.leyaogo.constants.CacheConfig;
import com.zhilianbao.leyaogo.constants.IntentConfig;
import com.zhilianbao.leyaogo.events.UserEventCode;
import com.zhilianbao.leyaogo.http.api.AccountApi;
import com.zhilianbao.leyaogo.http.callback.UploadMultiFileCallback;
import com.zhilianbao.leyaogo.model.response.UploadFileResponse;
import com.zhilianbao.leyaogo.model.response.UserLoginInfo;
import com.zhilianbao.leyaogo.model.response.me.UserDetailsInfo;
import com.zhilianbao.leyaogo.ui.fragment.address.ReceiveAddressFragment;
import com.zhilianbao.leyaogo.ui.fragment.base.BaseFragment;
import com.zhilianbao.leyaogo.utils.ImageUtils;
import com.zhilianbao.leyaogo.utils.Utils;
import com.zhilianbao.leyaogo.utils.XToastUtils;
import com.zhilianbao.leyaogo.view.dialog.AvatarSelectDialog;

import java.io.File;
import java.util.Date;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Response;

/**
 * Created by liu on 2016/10/24.
 * 用户中心
 */
public class UserInfoFragment extends BaseFragment implements View.OnClickListener {


    @BindView(R.id.row_avatar)
    CommonCircleRightListRow mRowAvatar;
    @BindView(R.id.row_receiveName)
    CommonListRow mRowReceiveName;
    @BindView(R.id.row_sign)
    CommonListRow mRowSign;
    @BindView(R.id.row_birth)
    CommonListRow mRowBirth;
    @BindView(R.id.row_sex)
    CommonListRow mRowSex;
    @BindView(R.id.row_my_address)
    CommonListRow mRowMyAddress;
    @BindView(R.id.row_real_name_authentication)
    CommonListRow mRealNameAuthentication;

    /**
     * 时间选择器
     */
    private TimePickerView mTimePickerView;
    private String nickName;
    private String sign;
    private String birthday;
    private String myAddress;
    private String sex;
    private PickPhotos.OnHandlerResultCallback mOnHandlerResultCallback;
    public int avatarSelect;
    public String realNameAuthentication;
    private UserDetailsInfo mUserDetailsInfo;
    private UserLoginInfo mUserLoginInfo;

    public static UserInfoFragment getInstance(/*UserDetailsInfo userDetailsInfo*/) {
        //        UserInfoFragment.mUserDetailsInfo = userDetailsInfo;
        UserInfoFragment fragment = new UserInfoFragment();
        return fragment;
    }

    @Override
    protected void initToolbarHere() {
        initToolbar(getString(R.string.user_info));
    }

    @Override
    protected void initViewsAndEvents(Bundle savedInstanceState) {
        mUserLoginInfo = Utils.getUserLoginInfo();
        mUserDetailsInfo = Utils.getUserInfo();
        setUserData();
        initTimePicker();
    }

    /**
     * 设置用户详细信息
     */
    private void setUserData() {
        ImageUtils.loadSmallAvatar(Utils.returnUrlShow(mUserDetailsInfo.getUserPic()), mRowAvatar.getImageRightIcon());
        nickName = StringUtils.isEmpty(mUserDetailsInfo.getNickName(), "");
        sign = StringUtils.isEmpty("每天进步一点点...", "");
        sex = StringUtils.isEmpty(Utils.getGenderString(mUserDetailsInfo.getSex()), "");
        birthday = StringUtils.isEmpty(mUserDetailsInfo.getBirthday(), "");
        myAddress = StringUtils.isEmpty("", "");
        realNameAuthentication = StringUtils.isEmpty("去认证", "");
        mRowSex.setStatusText(sex);
        mRowSex.setStatusTextColor(getResources().getColor(R.color.color_666666));
        mRowReceiveName.setStatusText(nickName);
        mRowReceiveName.setStatusTextColor(getResources().getColor(R.color.color_666666));
        mRowSign.setStatusText(sign);
        mRowSign.setStatusTextColor(getResources().getColor(R.color.color_666666));
        mRowBirth.setStatusText(birthday);
        mRowBirth.setStatusTextColor(getResources().getColor(R.color.color_666666));
        mRowMyAddress.setStatusText(myAddress);
        mRealNameAuthentication.setStatusText(realNameAuthentication);
        mRealNameAuthentication.setStatusTextColor(getResources().getColor(R.color.color_666666));
    }

    @Override
    protected int getContentViewLayoutID() {
        return R.layout.fragment_user;
    }

    @OnClick({R.id.row_avatar, R.id.row_receiveName, R.id.row_sign, R.id.row_birth, R.id.row_sex, R.id.row_my_address, R.id.row_real_name_authentication})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.row_avatar://头像
                //                showAvatarSelectDialog(new PickPhotos.OnHandlerResultCallback() {
                //                    @Override
                //                    public void onHandlerSuccess(int requestCode, List<String> resultList) {
                //                        ThreadPool.postOnUiDelayed(() -> AccountApi.uploadFile(mActivity, new File(resultList.get(0)), new UploadMultiFileCallback<UploadFileResponse>(mActivity) {
                //
                //                            @Override
                //                            public void onSuccess(UploadFileResponse uploadFileResponse, Call call, Response response) {
                //                                String md5filename = uploadFileResponse.getPicMD5();
                //                                mUserDetailsInfo.setUserPic(md5filename);
                //                                mUserLoginInfo.setUserPic(md5filename);
                //                                Utils.putUserLoginInfo(mUserLoginInfo);
                //                                Utils.updateUserInfor(mActivity, mUserDetailsInfo, mUserLoginInfo.getUserId(), mUserLoginInfo.getTokenId(), mUserLoginInfo.getUserId(), null, -1, md5filename, null, null);
                //                            }
                //                        }), 300);
                //
                //                    }
                //
                //                    @Override
                //                    public void onHandlerFailure(int requestCode, String errorMsg) {
                //
                //                    }
                //                });
                showAvatarSelectDialog(list -> {
                    if (CheckUtils.isEmpty(list.get(0).getCompressPath())) {
                        XToastUtils.showShortToast("图片获取失败");
                    } else {
                        ThreadPool.postOnUiDelayed(() -> AccountApi.uploadFile(mActivity, new File(list.get(0).getCompressPath()), new UploadMultiFileCallback<UploadFileResponse>(mActivity) {

                            @Override
                            public void onSuccess(UploadFileResponse uploadFileResponse, Call call, Response response) {
                                String md5filename = uploadFileResponse.getPicMD5();
                                mUserDetailsInfo.setUserPic(md5filename);
                                mUserLoginInfo.setUserPic(md5filename);
                                Utils.putUserLoginInfo(mUserLoginInfo);
                                Utils.updateUserInfor(mActivity, mUserDetailsInfo, mUserLoginInfo.getUserId(), mUserLoginInfo.getTokenId(), mUserLoginInfo.getUserId(), null, -1, md5filename, null, null);
                            }
                        }), 300);
                    }
                });
                break;
            case R.id.row_receiveName://昵称
                startForResult(EditInfoFragment.getInstance(0, nickName), 1000);
                break;
            case R.id.row_sign://个性签名
                startForResult(EditInfoFragment.getInstance(1, sign), 2000);
                break;
            case R.id.row_birth://生日
                if (mTimePickerView != null)
                    mTimePickerView.show();
                break;
            case R.id.row_sex://性别
                showSexSelectDialog();
                break;
            case R.id.row_my_address://我的地址
                start(ReceiveAddressFragment.getInstance(false));
                break;
            case R.id.row_real_name_authentication://实名认证
                break;
        }
    }

    /**
     * 旧版图片选择器对话框
     *
     * @param onHandlerResultCallback
     */
    public void showAvatarSelectDialog(PickPhotos.OnHandlerResultCallback onHandlerResultCallback) {
        mOnHandlerResultCallback = onHandlerResultCallback;
        AvatarSelectDialog avatarSelectDialog = new AvatarSelectDialog();
        Bundle bundle = new Bundle();
        bundle.putInt(IntentConfig.AVATAR_SELECT, avatarSelect);
        avatarSelectDialog.setArguments(bundle);
        avatarSelectDialog.setOnAvatarItemClickListener(new AvatarSelectDialog.OnAvatarItemClickListener() {
            @Override
            public void onTakePhotoClick() {//拍照
                PickPhotos.openCamera(2000, mOnHandlerResultCallback);
                avatarSelectDialog.dismiss();
            }

            @Override
            public void onPhotoAlbumClick() {//相册
                PickPhotos.openGallerySingle(1000, mOnHandlerResultCallback);
                avatarSelectDialog.dismiss();
            }
        });
        avatarSelectDialog.show(getFragmentManager(), "AvatarSelectDialog");
    }

    /**
     * 新版图片选择器对话框
     *
     * @param onHandlerResultCallback
     */
    public void showAvatarSelectDialog(PictureConfig.OnResultCallback onHandlerResultCallback) {
        FunctionConfig functionConfig = new FunctionConfig();
        functionConfig.setImageFolder(CacheConfig.IMAGE_COMPRESS_FOLDER);
        functionConfig.setImagePrefix(CacheConfig.IMAGE_PREFIX);
        PictureConfig.init(functionConfig);
        AvatarSelectDialog avatarSelectDialog = new AvatarSelectDialog();
        Bundle bundle = new Bundle();
        bundle.putInt(IntentConfig.AVATAR_SELECT, avatarSelect);
        avatarSelectDialog.setArguments(bundle);
        avatarSelectDialog.setOnAvatarItemClickListener(new AvatarSelectDialog.OnAvatarItemClickListener() {
            @Override
            public void onTakePhotoClick() {//拍照
                PictureConfig.getPictureConfig().openCamera(mActivity, onHandlerResultCallback);
                avatarSelectDialog.dismiss();
            }


            @Override
            public void onPhotoAlbumClick() {//相册
                PictureConfig.getPictureConfig().openPhoto(mActivity, onHandlerResultCallback);
                avatarSelectDialog.dismiss();
            }
        });
        avatarSelectDialog.show(getFragmentManager(), "AvatarSelectDialog");
    }

    public void showSexSelectDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(mActivity);
        builder.setView(R.layout.dialog_select_sex);
        AlertDialog ad = builder.create();  //创建对话框
        setDialogShowBottom(ad);
        ad.show();  //需先显示，然后才能查找控件
        TextView cancel = (TextView) ad.findViewById(R.id.dialog_cancel);
        TextView ok = (TextView) ad.findViewById(R.id.dialog_ok);
        RadioGroup sexSelect = (RadioGroup) ad.findViewById(R.id.rg_sex_select);
        RadioButton rbMan = (RadioButton) ad.findViewById(R.id.rb_man);
        RadioButton rbWoman = (RadioButton) ad.findViewById(R.id.rb_woman);
        RadioButton rbSecret = (RadioButton) ad.findViewById(R.id.rb_secret);

        //设置性别回显
        switch (mUserDetailsInfo.getSex()) {
            case 0://男
                sexColorSizeSet(rbWoman, rbSecret, rbMan);
                break;
            case 1://女
                sexColorSizeSet(rbMan, rbSecret, rbWoman);
                break;
            case 2://保密
                sexColorSizeSet(rbMan, rbWoman, rbSecret);
                break;
        }
        //设置性别选中变化显示
        sexSelect.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if (checkedId == rbMan.getId()) {
                    sexColorSizeSet(rbWoman, rbSecret, rbMan);
                } else if (checkedId == rbWoman.getId()) {
                    sexColorSizeSet(rbMan, rbSecret, rbWoman);
                } else {
                    sexColorSizeSet(rbMan, rbWoman, rbSecret);
                }
            }
        });
        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ad.dismiss();
            }
        });
        ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (sexSelect.getCheckedRadioButtonId() == rbMan.getId()) {
                    mUserDetailsInfo.setSex(0);
                } else if (sexSelect.getCheckedRadioButtonId() == rbWoman.getId()) {
                    mUserDetailsInfo.setSex(1);
                } else if (sexSelect.getCheckedRadioButtonId() == rbSecret.getId()) {
                    mUserDetailsInfo.setSex(2);
                }
                Utils.updateUserInfor(mActivity, mUserDetailsInfo, mUserLoginInfo.getUserId(), mUserLoginInfo.getTokenId(), mUserLoginInfo.getUserId(), null, mUserDetailsInfo.getSex(), null, null, null);
                ad.dismiss();
            }
        });
    }

    private void sexColorSizeSet(RadioButton rb1, RadioButton rb2, RadioButton rb3) {
        rb1.setTextColor(getResources().getColor(R.color.color_999999));
        rb1.setTextSize(13);
        rb2.setTextColor(getResources().getColor(R.color.color_999999));
        rb2.setTextSize(13);
        rb3.setTextColor(getResources().getColor(R.color.color_333333));
        rb3.setTextSize(15);
    }

    private void setDialogShowBottom(AlertDialog ad) {
        Window window = ad.getWindow();
        window.setGravity(Gravity.BOTTOM);
        window.setBackgroundDrawableResource(R.color.transparent);
        window.setWindowAnimations(R.style.DialogAnimation);  //添加动画
    }

    @Override
    protected void onFragmentResult(int requestCode, int resultCode, Bundle data) {
        super.onFragmentResult(requestCode, resultCode, data);
        if (data != null) {
            String result = data.getString(IntentConfig.USER_EDIT_USER_INFO, "");
            switch (resultCode) {
                //昵称
                case 0:
                    nickName = result;
                    mUserDetailsInfo.setNickName(result);
                    Utils.updateUserInfor(mActivity, mUserDetailsInfo, mUserLoginInfo.getUserId(), mUserLoginInfo.getTokenId(), mUserLoginInfo.getUserId(), null, -1, null, null, result);
                    break;
                //个性签名
                case 1:
                    sign = result;
                    mRowSign.setStatusText(result);
                    break;
            }
        }

    }

    /**
     * 初始化时间选择器
     */
    private void initTimePicker() {
        mTimePickerView = new TimePickerView(mActivity, TimePickerView.Type.YEAR_MONTH_DAY);
        mTimePickerView.setRange(1930, StringUtils.getCurrentYear());
        mTimePickerView.setTime(new Date());
        mTimePickerView.setCyclic(false);
        mTimePickerView.setCancelable(true);
        mTimePickerView.setTitle("选择日期");
        mTimePickerView.setTitleTextSizeColor(15, getResources().getColor(R.color.color_333333));
        mTimePickerView.setCancelTextSizeColor(15, getResources().getColor(R.color.color_333333));
        mTimePickerView.setSubmitTextSizeColor(15, getResources().getColor(R.color.color_333333));
        mTimePickerView.setStyle(1.1f, getResources().getColor(R.color.transparent), getResources().getColor(R.color.color_333333), getResources().getColor(R.color.color_999999), 9, 13);
        mTimePickerView.setOnTimeSelectListener(new TimePickerView.OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date) {
                birthday = DateUtils.format(date, "yyyy-MM-dd");
                mUserDetailsInfo.setBirthday(birthday);
                Utils.updateUserInfor(mActivity, mUserDetailsInfo, mUserLoginInfo.getUserId(), mUserLoginInfo.getTokenId(), mUserLoginInfo.getUserId(), birthday, -1, null, null, null);
            }
        });
    }

    @Override
    public boolean registerEventBus() {
        return true;
    }

    @Override
    protected void onHandleEvent(EventManager eventManager) {
        super.onHandleEvent(eventManager);
        switch (eventManager.getEventCode()) {
            case UserEventCode.MSG_CODE_MODIFY_USERINFO://更换用户信息成功,只有成功后才加载数据
                UserDetailsInfo userDetailsInfo = (UserDetailsInfo) eventManager.getData();
                ImageUtils.loadSmallAvatar(Utils.returnUrlShow(userDetailsInfo.getUserPic()), mRowAvatar.getImageRightIcon());
                int sex = userDetailsInfo.getSex();
                if (sex == 0) {
                    mRowSex.setStatusText("男");
                } else if (sex == 1) {
                    mRowSex.setStatusText("女");
                } else if (sex == 2) {
                    mRowSex.setStatusText("保密");
                }
                mRowReceiveName.setStatusText(userDetailsInfo.getNickName());
                mRowBirth.setStatusText(userDetailsInfo.getBirthday());
                break;
        }
    }

    @Override
    public boolean onBackPressedSupport() {
        if (mTimePickerView != null && mTimePickerView.isShowing()) {
            mTimePickerView.dismiss();
            return true;
        } else {
            return false;
        }
    }
}
